<?php

namespace App\Model\Service;

use App\AsyncTask\OcpcJobMessage;
use App\Helpers\OcpcUtil;
use App\Model\Ocpc\OcpcBaidu;
use App\Model\Ocpc\OcpcBaiduLog;
use App\Model\Ocpc\OcpcBaiduLoseLog;
use App\Model\Ocpc\OcpcBaiduUser;
use App\Model\Ocpc\OcpcUc;
use App\Model\Ocpc\OcpcUcLog;
use App\Model\Ocpc\OcpcUcLoseLog;
use App\Model\Ocpc\OcpcUcUser;
use App\Model\OcpcOppo;
use App\Model\OcpcOppoUser;
use App\Model\OcpcVivoLog;
use App\Model\OcpcXiaomiLog;
use App\Model\PayOrder;
use App\Model\User;
use App\Model\OcpcOppoLog;
/**
 * 回传处理service
 */
class OcpcService
{
    //激活
    const TYPE_ACTIVE = 1;
    //注册
    const TYPE_REG = 2;
    //付费
    const TYPE_PAY = 3;
    //首次付费
    const TYPE_FIRST_PAY = 4;

    private $info;
    private $eventType;

    public function __construct(OcpcJobMessage $message)
    {
        $this->info = $message->info;
        switch ($message->eventType) {
            case 'reg_done':
                $this->eventType = 2;
                break;
            case 'recharge':
                $this->eventType = 3;
                break;
            default:
                $this->eventType = 1;
                break;
        }
    }

    /**
     * 处理回传逻辑
     */
    public function handle()
    {
        log_info(__CLASS__ . "数据回传处理逻辑：".json_encode($this->info)."====".$this->eventType);
        $channel = $this->info['channel'] ?? '';
        if(in_array($channel,[408,508])){
            log_info('百度数据回传渠道'.$channel);
            $this->baiduOcpc();
        }elseif(in_array($channel,[405,505, 1005])){//小米
            $this->xiaomiOcpc(); //小米回传
        }elseif(in_array($channel,[503, 403, 1003])){//vivo
            $this->vivoOcpc(); //vivo
        }elseif(in_array($channel,[404,504, 1004])){//oppo数据回传
            $this->oppoOcpc(); //oppo回传
        }

        return true;
    }


    public function vivoOcpc(){
        if (empty($this->info['imei']) && empty($this->info['oaid'])) return;
        $flag = date('Y-m-d') === date('Y-m-d',strtotime($this->info['created_at'])) ? 1 : 0;

        //充值
        if($this->eventType==self::TYPE_PAY ){
            if($flag == 0) return ;
            //查询充值订单
            $check = PayOrder::checkSuccessCounts($this->info['user_id']);
            if ($check>1) {
                return ;
            }
            $where = [
                ['user_id', $this->info['user_id']],
                ['type',7]
            ];
            $log = OcpcVivoLog::where($where)->count() ?? 0;
            if($log>1) return ;
        }
        $data = OcpcUtil::pushVivo($this->eventType, $this->info);
        log_info(__CLASS__ . "vivoOcpc+++".json_encode($data));
        $data['is_register'] = date('Y-m-d') === date('Y-m-d',strtotime($this->info['created_at'])) ? 1 : 0;
        OcpcVivoLog::insert([
            'user_id' => $data['user_id'],
            'oaid'=>$data['oaid'],
            'imei'=>$data['imei'],
            'pay_amount'=>$data['pay_amount'],
            'pkg'=>$data['pak'],
            'res'=>$data['res'],
            'is_register' => $data['is_register'],
            'type'=>$this->eventType,
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s'),
        ]);
        return;
    }

    /**
     * 小米推广
     */
    public function xiaomiOcpc(){
        if (empty($this->info['imei']) && empty($this->info['oaid'])) return;
        $flag = date('Y-m-d') === date('Y-m-d',strtotime($this->info['created_at'])) ? 1 : 0;

        //充值
        if($this->eventType==self::TYPE_PAY){
            if($flag == 0) return ;
            //查询充值订单
            $check = PayOrder::checkSuccessCounts($this->info['user_id']);
            if ($check>1) {
                return ;
            }
            $where = [
                ['user_id', $this->info['user_id']],
                ['type',3]
            ];
            $log = OcpcXiaomiLog::where($where)->count() ?? 0;
            if($log>1) return ;
        }
        $data = OcpcUtil::pushXiaoMi($this->eventType, $this->info);
        if(empty($data)) return ;
        log_info(__CLASS__ . "xiaomiOcpc+++".json_encode($data));
        $data['is_register'] = date('Y-m-d') === date('Y-m-d',strtotime($this->info['created_at'])) ? 1 : 0;
        OcpcXiaomiLog::insert([
            'user_id' => $data['user_id'],
            'oaid'=>$data['oaid'],
            'imei'=>$data['imei'],
            'pay_amount'=>$data['pay_amount'],
            'pkg'=>$data['pak'],
            'res'=>$data['res'],
            'is_register' => $data['is_register'],
            'type'=>$this->eventType,
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s'),
        ]);

        // 如果是付费，则再上报一次首次付费
        if ($this->eventType == self::TYPE_PAY) {
            $this->addXmFirstPay($this->info);
        }

        return;
    }

    /**
     * 小米首次付费上报
     * @param $info
     * @return void
     */
    public function addXmFirstPay($info)
    {
        $data = OcpcUtil::pushXiaoMi(self::TYPE_FIRST_PAY, $info);
        if (empty($data)) return;
        log_info(__CLASS__ . "+xiaomiOcpc——FirstPay+++" . json_encode($data));
        $data['is_register'] = date('Y-m-d') === date('Y-m-d', strtotime($info['created_at'])) ? 1 : 0;

        OcpcXiaomiLog::insert([
            'user_id'     => $data['user_id'],
            'oaid'        => $data['oaid'],
            'imei'        => $data['imei'],
            'pay_amount'  => $data['pay_amount'],
            'pkg'         => $data['pak'],
            'res'         => $data['res'],
            'is_register' => $data['is_register'],
            'type'        => self::TYPE_FIRST_PAY,
            'created_at'  => date('Y-m-d H:i:s'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ]);
        return;
    }

    /**
     * 回传注册至Oppo并记录
     */
    public function oppoOcpc()
    {
        if (empty($this->info['imei']) && empty($this->info['oaid'])) return;

        // 判断是否oppo归因
        $ocpoInfo = OcpcOppoUser::getUrlByUserId($this->info['user_id'], $this->info['channel']);
        if (empty($ocpoInfo)) {
            $ocpoInfo = $this->relationOppoAndUser($this->info);
            if (empty($ocpoInfo)) {
                return ;
            }
        }

        $flag = date('Y-m-d') === date('Y-m-d',strtotime($this->info['created_at'])) ? 1 : 0;
        //充值
        if($this->eventType==self::TYPE_PAY){
            if($flag == 0) return ;
            //查询充值订单
            $check = PayOrder::checkSuccessCounts($this->info['user_id']);
            if ($check>1) {
                return ;
            }
            $where = [
                ['user_id', $this->info['user_id']],
                ['type',3]
            ];
            $log = OcpcXiaomiLog::where($where)->count() ?? 0;
            if($log>1) return ;
        }

        log_info('回传注册至Oppo并记录'.$this->eventType."++++用户数据".json_encode($this->info));

        $data = OcpcUtil::pushOppo($this->eventType, $this->info, $ocpoInfo['ad_id']);

        $data['is_register'] = date('Y-m-d') === date('Y-m-d',strtotime($this->info['created_at'])) ? 1 : 0;

        OcpcOppoLog::addLog($data);
        return;
    }

    /**
     * 首次进行Oppo渠道用户关联
     * @return false|mixed
     */
    private function relationOppoAndUser($info)
    {
        $log = OcpcOppo::handleSearch($info);

        if (!$log) {
            log_info(__CLASS__ . "==relationOppoAndUser==" . json_encode($info) . "===false");

            return false;
        }

        $_insert = [
            'user_id' => $info['user_id'],
            'ocpc_id' => $log['id'],
            'channel_id' => $log['channel_id'],
            'ad_id' => $log['ad_id']
        ];

        OcpcOppoUser::addRelation($_insert); //回传信息与用户进行关联

        return $log;
    }

    /**
     * 确定是否百度来源
     */
    private function baiduOcpc()
    {
        log_info('确定是否百度来源'.json_encode($this->info));
        $info = OcpcBaiduUser::getUrlByUserId($this->info['user_id'], $this->info['channel']);
        $url = empty($info['url']) ? '' : $info['url'];
        if (empty($info)) {
            $info = $this->relationBaiduAndUser($this->info);
            $url =  empty($info['callback_url']) ? '' : $info['callback_url'];
        }
        log_info('百度URL'.$url.json_encode($info));
        if (!$url) return false;
        $data = [
            'url' => $url,
            'pay_amount' => 0,
            'channel' => $this->info['channel']
        ];
        $akeys = $info['akeys'];
        log_info('百度数据来源'.json_encode($data));
        switch ($this->eventType) {
            case 2:
                $log = OcpcUtil::pushBaidu(1, $data,$akeys);
                $log['user_id'] = $this->info['user_id'];
                if ($log) OcpcBaiduLog::addLog($log);
                $log = OcpcUtil::pushBaidu(2, $data,$akeys);
                $log['user_id'] = $this->info['user_id'];
                if ($log) OcpcBaiduLog::addLog($log);
                break;
            case 3:
                $data['pay_amount'] = $this->info['pay_amount'];
                $log = OcpcUtil::pushBaidu(3, $data,$akeys);
                $log['user_id'] = $this->info['user_id'];
                if ($log) OcpcBaiduLog::addLog($log);
                break;
            default:
                $log = OcpcUtil::pushBaidu(1, $data,$akeys);
                $log['user_id'] = $this->info['user_id'];
                if ($log) OcpcBaiduLog::addLog($log);
                break;
        }
        log_info('来源数据线'.json_encode($log));
        return true;
    }

    /**
     * 首次进行baidu渠道用户关联
     * @return false|mixed
     */
    private function relationBaiduAndUser($info)
    {
        $log = OcpcBaidu::handleSearch($info);
        if (!$log) {
            //从缺失oaid中获取一条
            $log = OcpcBaiduLoseLog::shift($info['channel']);
            if (!$log) {
                log_info(__CLASS__ . "==getBaiduOcpc==" . json_encode($info) . "===false");
                return false;
            }
        }
        $_insert = [
            'user_id' => $info['user_id'],
            'ocpc_id' => $log['id'],
            'url' => $log['callback_url'],
            'channel' => $log['channel'],
            'akeys' => $log['akeys'],
        ];
        OcpcBaiduUser::addRelation($_insert); //回传信息与用户进行关联
        return $log;
    }


    /**
     * 确定是否Uc来源
     */
    private function ucOcpc()
    {
        $url = OcpcUcUser::getUrlByUserId($this->info['user_id'], $this->info['channel']);
        if (!$url) {
            $url = $this->relationUcAndUser($this->info);
        }
        if (!$url) return false;
        $data = [
            'url' => $url,
            'pay_amount' => 0,
            'channel' => $this->info['channel'],
            'oaid' => $this->info['oaid']
        ];

        switch ($this->eventType) {
            case 2:
                $log = OcpcUtil::pushUc(1, $data);
                $log['user_id'] = $this->info['user_id'];
                if ($log) OcpcUcLog::addLog($log);
                $log = OcpcUtil::pushUc(2, $data);
                $log['user_id'] = $this->info['user_id'];
                if ($log) OcpcUcLog::addLog($log);
                break;
            case 3:
                $data['pay_amount'] = $this->info['pay_amount'];
                $log = OcpcUtil::pushUc(3, $data);
                $log['user_id'] = $this->info['user_id'];
                if ($log) OcpcUcLog::addLog($log);
                break;
            default:
                $log = OcpcUtil::pushUc(1, $data);
                $log['user_id'] = $this->info['user_id'];
                if ($log) OcpcUcLog::addLog($log);
                break;
        }
        return true;
    }

    /**
     * 首次进行baidu渠道用户关联
     * @return false|mixed
     */
    private function relationUcAndUser($info)
    {
        $log = OcpcUc::handleSearch($info);
        if (!$log) {
            //从缺失oaid中获取一条
            $log = OcpcUcLoseLog::shift($info['channel']);
            if (!$log) {
                log_info(__CLASS__ . "==getUcOcpc==" . json_encode($info) . "===false");
                return false;
            }
        }
        $_insert = [
            'user_id' => $info['user_id'],
            'ocpc_id' => $log['id'],
            'url' => $log['callback_url'],
            'channel' => $log['channel']
        ];
        OcpcUcUser::addRelation($_insert); //回传信息与用户进行关联
        return $log['callback_url'];
    }
}
